package com.dongdongshop.controller;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.dongdongshop.service.SmsService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RocketMQMessageListener(consumerGroup = "dk2208-topic", topic = "dk2208-topic")
public class MqController implements RocketMQListener<String> {
    @Autowired
    private AsyncClient client;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SmsService smsService;
    @Override
    public void onMessage(String phoneNum) {
        String s = RandomUtil.randomNumbers(6);
        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName("东科创想")
                .templateCode("SMS_162522027")
                .templateParam("{\"sms_code\":\""+s+"\"}")
                .phoneNumbers(phoneNum)
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        SendSmsResponse resp = null;
        try {
            resp = response.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println(new Gson().toJson(resp));
        //如果操作成功将验证码存入redis并设置过期时间
        redisTemplate.boundValueOps(phoneNum).set(s);
        //设置过期时间30分钟
        redisTemplate.expire(phoneNum,30, TimeUnit.MINUTES);
    }
}
